<template>
  <div class="task-view-output common-code-table">
    <div class="table-code-content">
      <div class="filepath-header">
        <div class="filepath-header-left">
          <img class="file-icon" src="@/common/image/icon/folder.png">
          <div class="breadcrumb" v-if="curFilePath === '/'">
            <span class="file-path" @click="clickFilePath('/')">/output</span>
          </div>
          <div class="breadcrumb" v-else>
            <span class="file-path" @click="clickFilePath('/')">/output</span>
            <span class="file-path" v-for="(item, key) in filePath.slice(1)" :key="key" @click="clickFilePath(item, key)">/{{item}}</span>
          </div>
        </div>
        <div class="filepath-header-right">
          <el-button-group>
            <!-- <el-button size="small" @click="createDateSetByOutput" :disabled="fileList.length === 0">生成数据集</el-button> -->
            <!-- <el-button size="small" @click="downLoadFile" :disabled="multipleSelection.length === 0">下载</el-button> -->
          </el-button-group>
        </div>
      </div>
      <div v-show="showEditor === 0">
        <div class="file-table">
          <el-table
            ref="multipleTable"
            :data="fileList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :header-row-class-name="handleTableHeaderclass">
            <!-- <el-table-column type="selection" width="40"></el-table-column> -->
            <el-table-column
              label="文件/文件夹名称">
              <template slot-scope="scope">
                <div class="table-link" @click="clickTableRow(scope.row)">
                  <i :class="{'file-pic': scope.row.isImg, 'file-icon': !scope.row.directory && !scope.row.isImg, 'folder-icon': scope.row.directory}"></i>
                  <span>{{ scope.row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新日期">
              <template slot-scope="scope">
                <span>{{ new Date(scope.row.updateTime).Format("yyyy-MM-dd hh:mm:ss") }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="size"
              label="大小"
              width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.size ? scope.row.size : '--' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="basePagenate">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-size="pageSize"
              :current-page="pageNumber"
              :total="totalPage"
              layout="prev, pager, next">
            </el-pagination>
          </div>
        </div>
        <div class="markdown-box" v-if="showMarkdown">
          <div class="header-markdown">
            <span class="header-left"><img src="@/common/image/icon/book-open-variant.png">README.md</span>
            <span v-if="!editMarkdown" class="header-right" @click="doEditMarkdown"><i class="el-icon-edit-outline"></i>编辑</span>
            <span v-else class="header-right"><i class="icon-save" /><span @click="doSaveMarkdown">保存</span><i class="icon-cancle" /><span @click="doCancleMarkdown">取消</span></span>
          </div>
          <viewer
            v-show="!editMarkdown"
            :value="readmeData"
            height="500px"
            class="markdown-content"
          />
          <editor
            v-show="editMarkdown"
            ref="tuiEditor"
            v-model="readmeData"
            :options="editorOptions"
            previewStyle="vertical"
            height="500px"
          />
        </div>
      </div>
    </div>
    <div v-show="showEditor === 1" class="editor-container">
      <div class="editor-header">
        <span>{{curEditFile.fileName}}</span>
        <div v-show="showEdit" class="action r action-right"><i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span></div>
      </div>
      <div class="code-eidtor">
        <div ref="container" id="container" style="width:100%;height:700px;border:1px solid #ddd"></div>
      </div>
    </div>
    <div v-show="showEditor === 2" class="editor-container">
      <div class="editor-header">
        <span>{{curEditFile.fileName}}</span>
        <div v-show="!showMDEdit" class="action r action-right"><i class="icon-cancle" /><span class="action-span-hover" @click="doCancle">取消</span></div>
      </div>
      <viewer
        v-show="!showMDEdit"
        :value="markdownData"
        height="500px"
        class="md-content"
      />
      <editor
        v-show="showMDEdit"
        ref="mdEditor"
        v-model="markdownData"
        :options="editorOptions"
        previewStyle="vertical"
        height="500px"
      />
    </div>
    <el-dialog
      title="图片浏览"
      :visible.sync="dialog.picPreview"
      :pos="'center'"
      width="40%">
      <div class="file-panel picPreview">
        <img :src="curPicPreView" />
      </div>
      <!-- <div slot="footer" class="dialog-footer basebtn">
        <div>
          <button @click="dialog.picPreview=false" class="dialog-button active last">关 闭</button>
        </div>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import 'tui-editor/dist/tui-editor.css'
import 'tui-editor/dist/tui-editor-contents.css'
import 'codemirror/lib/codemirror.css'
import { Editor, Viewer } from '@toast-ui/vue-editor'

import * as monaco from 'monaco-editor'

import { getPublicJobOutPutFileList } from '@/api/filecenter'
import { verifyFileType } from '@/common/js/utils'
import axios from 'axios'
import { mapGetters } from 'vuex'

export default {
  props: {
    curTask: Object
  },
  data () {
    return {
      // Table勾选项
      multipleSelection: [],
      // 当前文件路径
      curFilePath: '/',
      // 文件路径
      filePath: ['/'],
      // 总页数
      totalPage: 0,
      // 每页条数
      pageSize: 10,
      // 当前页
      pageNumber: 1,
      // 文件列表
      fileList: [],
      // 显示编辑器
      showEditor: 0,
      // 展示Markdown
      showMarkdown: false,
      // 编辑器显示编辑按钮
      showEdit: true,
      showMDEdit: false,
      // 编辑器是否可编辑
      readOnly: true,
      // 文件内容
      fileContent: '',
      // md文件内容
      markdownData: '',
      // 当前编辑文件
      curEditFile: '',
      // 当前浏览图片
      curPicPreView: '',
      clickFileBtn: true,
      // 弹窗显隐
      dialog: {
        picPreview: false
      },
      editorOptions: {
        hideModeSwitch: true
      }
    }
  },
  watch: {
    curTask: function (newVal, oldVal) {
      this._getFileList('/')
    }
  },
  mounted () {
    if (this.curTask.projectId) {
      this._getFileList('/')
    }
  },
  methods: {
    // 生成数据集
    createDateSetByOutput () {
      if (this.fileList.length === 0) {
        return false
      }
      this.$router.push({ path: '/dataset/create', query: { projectId: this.curTask.projectId, jobName: this.curTask.jobName, createByOutput: true } })
    },
    // 下载
    downLoadFile () {
      if (this.multipleSelection.length === 0) {
        return false
      }
      let dirs = ''
      const separator = this.curFilePath === '/' ? '' : '/'
      this.multipleSelection.map((item, index) => {
        if (index === 0) {
          dirs = 'dirs=' + this.curFilePath + separator + item.fileName
        } else {
          dirs = dirs + '&dirs=' + this.curFilePath + separator + item.fileName
        }
      })
      const fileUrl = `/gateway/fileCenter/api/file/jobOutputFileDownload?jobName=${this.curTask.jobName}&projectId=${this.curTask.projectId}&${dirs}&token=${this.userInfo.token}&bitaToken=${this.userInfo.bitaToken}`
      window.open(fileUrl, '_blank')
      // 下载完成，清空Table用户选择
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection()
    },
    // 点击文件路径
    clickFilePath (val, key) {
      this.showEditor = 0
      this.showMDEdit = false
      this.pageNumber = 1
      if (val === '/') {
        this._getFileList(val)
        this.curFilePath = '/'
        this.filePath = ['/']
      } else {
        let path = ''
        let pathArr = this.filePath.slice(0, key + 2)
        this.filePath = pathArr
        pathArr.map((item, index) => {
          if (index === 0) {
            path = item
          } else if (index === 1) {
            path = path + item
          } else {
            path = `${path}/${item}`
          }
        })
        this.curFilePath = path
        this._getFileList(path)
      }
    },
    // 点击Table列
    clickTableRow (row) {
      if (row.directory) {
        this.goToFolder(row.fileName)
        this.showEditor = 0
      } else if (row.isImg) {
        this.dialog.picPreview = true
        this._previewImg(row).then(res => {
          this.curPicPreView = URL.createObjectURL(res)
        })
      } else {
        let fileType = row.fileName.replace(/.+\./, '')
        if (fileType === 'md') {
          this.curEditFile = row
          this.fileContent = ''
          this._getFileContent(row.fileName, true)
          this.showEditor = 2
        } else if (verifyFileType(fileType)) {
          this.curEditFile = row
          this.fileContent = ''
          this._getFileContent(row.fileName)
          this.showEditor = 1
        } else {
          this.$message({ message: '暂不支持该文件类型预览', showClose: true, type: 'warning' })
        }
      }
    },
    // 点击文件夹
    goToFolder (dir) {
      if (this.clickFileBtn) {
        this.pageNumber = 1
        this.clickFileBtn = false
        if (this.curFilePath === '/') {
          this.curFilePath = `/${dir}`
        } else {
          this.curFilePath = `${this.curFilePath}/${dir}`
        }
        this.filePath.push(dir)
        this._getFileList(this.curFilePath)
      }
    },
    doCancle () {
      this.showEditor = 0
    },
    // Table多选操作
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 分页
    handleSizeChange (val) {
      this.pageSize = val
      this.pageNumber = 1
      this._getFileList(this.curFilePath)
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      this._getFileList(this.curFilePath)
    },
    handleTableHeaderclass () {
      return 'table-head-th'
    },
    /*
      --------------接口调用--------------
    */
    // 查询文件列表
    _getFileList (path) {
      let para = `?projectId=${this.curTask.projectId}&dir=${path}&pageNumber=${this.pageNumber}&pageSize=${this.pageSize}&jobName=${this.curTask.jobName}`
      getPublicJobOutPutFileList(para).then(res => {
        if (res.message.code === 0) {
          this.totalPage = res.data.totalCount
          // 判断是否是图片
          const imgExt = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
          if (res.data.fileList) {
            this.fileList = res.data.fileList
            this.fileList.forEach(el => {
              let isImg = imgExt.contain(el.fileName.extension())
              el.isImg = isImg
              if (isImg) {
                let preOpt = {}
                let separator = this.curFilePath === '/' ? '' : '/'
                preOpt.src = `/gateway/fileCenter/api/file/preview?dir=${this.curFilePath + separator + el.fileName}&projectId=${this.curTask.projectId}&jobName=${this.curTask.jobName}`
                el.preOpt = preOpt
              }
            })
          }
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
        this.clickFileBtn = true
      })
    },
    /*
      description: 下载文件内容
      fileName: 文件名
      isMDFile: 是否markdown类型文件
    */
    _getFileContent (fileName, isMDFile = false) {
      let separator = ''
      let fileUrl = ''
      if (fileName) {
        separator = this.curFilePath === '/' ? '' : '/'
        fileUrl = `/gateway/fileCenter/api/file/publicJobOutput/preview?dir=${this.curFilePath + separator + fileName}&projectId=${this.curTask.projectId}&jobName=${this.curTask.jobName}`
      } else {
        fileUrl = `/gateway/fileCenter/api/file/publicJobOutput/preview?dir=/README.md&projectId=${this.curTask.projectId}&jobName=${this.curTask.jobName}`
      }
      axios({
        method: 'get',
        url: fileUrl
      }).then(res => {
        if (fileName && !isMDFile) {
          this.fileContent = res.data
          this.$refs.container.innerHTML = ''
          this.editor = monaco.editor.create(document.getElementById('container'), {
            value: '',
            language: 'python',
            readOnly: true
          })
          if (typeof this.fileContent === 'object') {
            this.fileContent = res.request.response
            this.fileContentOriginal = res.request.response
            this.editor.setValue(this.fileContent)
          } else {
            this.editor.setValue(String(this.fileContent))
          }
        } else if (fileName && isMDFile) {
          if (res.data === '') {
            this.showEditor = 0
          } else {
            this.showEditor = 2
            this.markdownData = res.data
            this.fileContentOriginal = res.data
          }
        } else {
          if (res.data === '') {
            this.showMarkdown = false
          } else {
            this.showMarkdown = true
            this.readmeData = res.data
            this.fileContentOriginal = res.data
          }
        }
      })
    },
    // 预览图片
    _previewImg (row) {
      let separator = this.curFilePath === '/' ? '' : '/'
      let fileUrl = `/gateway/fileCenter/api/file/preview?dir=${this.curFilePath + separator + row.fileName}&projectId=${this.curTask.projectId}&jobName=${this.curTask.jobName}`
      return axios({
        method: 'get',
        url: fileUrl,
        responseType: 'blob',
        emulateJSON: true
      }).then(res => {
        return Promise.resolve(res.data)
      })
    }
  },
  components: {
    'editor': Editor,
    'viewer': Viewer
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  }
}
</script>

<style lang="stylus" scoped>
@import "../../common/stylus/common_code_table"
.task-view-output
  background #ffffff
</style>
